'''
#Coding: utf-8
#Project: online-exam
#Author: rtf
#Time: 2022-07-27 11:23:19
#FileName: menu.py
#Softwar: PyCharm
'''


import json
from trump.utils import get_user
from trump.query import get_item, get_items
from trump.utils import ok, fail
from utils.recursion_tree import get_list
from utils.params_validate_decorator import validate_params


async def ls(app, request):
    role_code = get_user(request).get("role")
    if "SYSTEM_MANAGER" not in role_code:
        menus = await get_items(app.ctx.pool, "menu", {"role_code-contains": role_code, "sort": "-priority"})
    else:
        menus = await get_items(app.ctx.pool, "menu", {"sort": "-priority"})
    data = get_list('0', menus, parent_column_name="parent", next_parent_column_name="menu_code")

    return ok(data)


@validate_params([["parent", str, True], ["menu_name", str, True], ["menu_code", str, True],
                  ["icon", str, False], ["role_codes", str, False], ["url", str, False],
                  ["enabled", int, False], ["priority", int, True], ["buttons", list, False],
                  ["menu_type", str, False]])
async def post(app, request):
    params = request.json
    parent = params.get("parent")

    menu = await get_item(app.ctx.pool, "menus", params.get("menu_name"), column="menu_name")
    if menu:
        return fail(data="菜单已存在！", return_msg="菜单已存在！")

    if str(parent) != "0":
        # if not params.get("buttons"):
        #     return fail("缺少buttons！")
        menu = await get_item(app.ctx.pool, "menus", parent, column="menu_code")
        if not menu:
            return fail(data="parent 不存在！", return_msg="parent 不存在！")
    if params.get("buttons"):
        params["buttons"] = json.dumps(params.get("buttons"), ensure_ascii=False)


@validate_params([["parent", str, True], ["menu_name", str, True],
                  ["icon", str, False], ["role_codes", str, False], ["url", str, False],
                  ["enabled", int, False], ["priority", int, True], ["buttons", list, False],
                  ["menu_type", str, False]])
async def put(app, request, id):
    params = request.json

    parent = params.get("parent")

    # menu = await get_item(app.ctx.pool, "menus", params.get("menu_name"), column="menu_name")
    # if menu:
    #     return fail(return_msg="菜单已存在！")

    if str(parent) != "0":
        # if not params.get("buttons"):
        #     return fail(data="缺少buttons！", return_msg="缺少buttons！")
        menu = await get_item(app.ctx.pool, "menus", parent, column="menu_code")
        if not menu:
            return fail(data="parent 不存在！", return_msg="parent 不存在！")

    params["buttons"] = json.dumps(params.get("buttons"), ensure_ascii=False)


async def delete(app, request, id):
    pass